from app01 import models
from django import forms
from django.core.validators import RegexValidator
from app01.utilss.BootStrapModelform import BootStrapModelform


class UserModelForm(BootStrapModelform):
    name = forms.CharField(min_length=3,label = '用户名')#验证规则
    account = forms.DecimalField(label='账户余额',max_digits=10, decimal_places=2)
    class Meta:
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'gender', 'depart', 'create_time']
        # widgets = {
        #     'name': forms.TextInput(attrs={'class': 'form-control'}),
        #     'password': forms.PasswordInput(attrs={'class': 'form-control'}),
        #     'age': forms.NumberInput(attrs={'class': 'form-control'}),
        #     'account': forms.NumberInput(attrs={'class': 'form-control'}),
        #     'gender': forms.Select(attrs={'class': 'form-control'}),
        #     'depart': forms.Select(attrs={'class': 'form-control'}),
        # }


class PrettyModelForm(BootStrapModelform):
    num = forms.CharField(
        label='手机号码',
        validators=[
            # 自定义验证规则
            # 1. 验证规则函数
            # 2. 错误信息
            # 3. 验证规则函数的参数
            RegexValidator(r'^1[3-9]\d{9}$', '手机号码格式错误')
        ]
    )

    class Meta:
        model = models.Prettynum
        fields = ['num', 'price', 'level', 'status']

    def clean_num(self):
        num = self.cleaned_data['num']
        exists = models.Prettynum.objects.filter(num=num).exists()
        if exists:
            raise forms.ValidationError('该手机号已存在')
        return num

class AdminModelForm(BootStrapModelform):
    confirm_password = forms.CharField(
        label='确认密码',
        widget=forms.PasswordInput(render_value=True),
    )
    class Meta:
        model = models.Admin
        fields = ['username', 'password']
        widgets = {
            'password': forms.PasswordInput(render_value=True),
        }
    def clean(self):
        cleaned_data =super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')
        if password != confirm_password:
            raise forms.ValidationError('两次密码不一致')
        return cleaned_data